var salt = sessionStorage.getItem('usersalt');
var maxEstimateNum = 0;
var id = getQueryVariable('id');
var optionType = 0;

var app = new Vue({
  el: ".body",
  data: {
    list: [],
    questionType: '',
    baseurl: url,
    info: ''
  },
  updated: function () {
    layui.use(['form'], function () {
      var form = layui.form;
      form.render('checkbox');
      form.render('radio');
      form.render('select');
    });
  }
})
layui.use(['form', 'layer', 'laydate', 'table', 'laytpl'], function () {
  var form = layui.form,
      layer = parent.layer === undefined ? layui.layer : top.layer,
      $ = layui.jquery,
      laydate = layui.laydate,
      laytpl = layui.laytpl,
      table = layui.table;

  if (!sessionStorage.getItem('username')) {
    layer.msg('请先登录');
    setTimeout("top.location.href='../../../index.html'", 1000);
  }


  layui.use('upload', function () {
    var $ = layui.jquery,
        upload = layui.upload;

    upload.render({
      elem: '.file',
      url: url + 'attachment/upload',
      multiple: true,
      exts: 'png|jpg|gif|jpeg|PNG|JPG|GIF|JPEG',
      // exts: 'pdf',
      before: function (obj) {
      },
      done: function (res, index) {
        //上传完毕
        if (res.code == 0) {
          var fileId = $(this.item).attr("fileId") ? res.data.id : $(this.item).attr("fileId") + "," + res.data.id;
          $(this.item).attr("fileId", fileId);
          var img = $('<div style="display:inline-block;position:relative;margin-top:10px;margin-left:20px;" ><div id="' + res.data.id + '" class="delImg" style="position:absolute;top:-4px;right:-5px;color:white;background:red;border:1px solid red;border-radius:50%;width:16px;height:16px"><i class="layui-icon" style="position:relative;top:0px;right:0px;">&#x1006;</i></div><img id="pic' + res.data.id + '" src="' + url + 'attachment/seekFile/' + res.data.id + '" width="100px" height="100px" class="picsty"/></div>');
          $(this.item).parent().append(img);
        }
      }
    });

  });

  form.on('select(questionType)', function (data) {
    optionType = data.value;
    console.log(data.value);
    sortOption();
  });

  form.on('checkbox', function (data) {
    if (data.elem.checked) {
      $(this).siblings(".true").show()
    } else {
      $(this).siblings(".true").hide()
    }
  });
  form.on('radio', function (data) {
    $(".option .true").hide();
    $(this).siblings(".true").show();
  });


  $.post(url + 'question/getTypeName', {Token: salt}, function (data) {
    if (data.code == 0) {
      var list = data.data;
      var opt = '<option value="0">请选择</option>'
      for (var i = 0; i < list.length; i++) {
        opt += '<option value="' + list[i].id + '" >' + list[i].name + '</option>'
      }
      $('#typeName').append(opt);
      $.post(url + 'question/getDifferServ', {Token: salt}, function (data) {
        if (data.code == 0) {
          var list = data.data;
          var opt = '<option value="">请选择</option>'
          for (var i = 0; i < list.length; i++) {
            opt += '<option value="' + list[i].id + '" >' + list[i].name + '</option>'
          }
          $('#differServ').append(opt);
          form.render();
          getData()
        } else {
          alert(data.msg);
        }
      })
    } else {
      alert(data.msg);
    }
    console.log(data);
  })


});


$("body").on("click", ".model .button button", function () {
  $(".model").hide()
});

var letterArr = [];
for (var i = 65, j = 0; i < 91; i++, j++) {
  letterArr[j] = String.fromCharCode(i);
}

//选项排序
sortOption()
function sortOption() {
  $(".option label").each(function (i) {
    $(this).text(letterArr[i]);
  })
  if (optionType == 2) {
    $(".type_option input").hide().siblings().show();
    $(".add_option").hide();
  } else {
    $(".type_option input").show().siblings().hide();
    $(".add_option").show();
  }

  if (optionType == 1) {
    $(".option input[type=radio]").attr("type", "checkbox");
    $(".option .layui-form-radio").remove()
  } else if (optionType == 2) {
    $(".option input[type=checkbox]").attr("type", "radio");
    $(".option .layui-form-checkbox").remove();
    $(".option").each(function (index) {
      if (index > 1) {
        $(this).remove()
      } else if (index == 0) {
        $(this).find(".type_option span").text("正确")
      } else if (index == 1) {
        $(this).find(".type_option span").text("错误")
      }
    })
  } else {
    $(".option input[type=checkbox]").attr("type", "radio");
    $(".option .layui-form-checkbox").remove()
  }

  // $(".option input[type=checkbox],.option input[type=radio]").prop("checked",false);
  // $(".option .true").hide();

  layui.use(['form'], function () {
    var form = layui.form;
    form.render('checkbox');
    form.render('radio');
    form.render('select');
  });
}

//添加选项
$("body").on("click", ".add_option .box", function () {
  var input_type = optionType == 1 ? "checkbox" : "radio";
  var str = '<div class="layui-input-block option">' +
      '<label></label><input type="' + input_type + '" name="option" lay-skin="primary">' +
      '<span class="type_option" style="margin-left: 50px;margin-right: 3px;">' +
      '<input type="text" name="title" lay-verify="title" autocomplete="off" placeholder="请输入标题"' +
      'class="layui-input option_input"><span>错误</span></span>' +
      '<i class="seraph icon-guanbi"></i>' +
      '<span class="true" style="display: none;">【正解】</span><div><button type="button" class="layui-btn layui-btn-normal file">选择图片</button></div>';
  $(".add_option").before(str);
  sortOption();
})

//提交
$("body").on("click", ".commit", function () {
  var differServ = $("#differServ").val();
  var typeName = $("#typeName").val();
  var questionType = $("#questionType").val();
  var title = $("#title").val();
  var fileId = getField($("#fileId"));
  var parse = $("#parse").val();
  var parseFileId = getField($("#parseFileId"));
  var option = [];
  var optionValue;
  if (!differServ || !typeName || !title) {
    alert("请完善内容");
    return
  }
  $(".option").each(function (i) {
    var key = $(this).find("label").text();
    var value = optionType == 2 ? $(this).find(".type_option span").text() : $(this).find(".option_input").val();
    var fileId = $(this).find("button").attr("fileId") ? $(this).find("button").attr("fileId") : '';
    var answer;
    if (questionType == 1) {
      answer = $(this).find(".layui-form-checkbox").hasClass('layui-form-checked') ? 1 : 0
    } else {
      answer = $(this).find(".layui-form-radio").hasClass('layui-form-radioed') ? 1 : 0
    }
    var obj = {
      key: key,
      value: value,
      fileId: fileId,
      answer: answer
    };
    if (!key || !value) {
      optionValue = false;
      alert("请完善选项内容");
      return
    } else {
      optionValue = true;
    }
    option.push(obj)
  })
  if (!optionValue) {
    return
  }
  if (option.every(function (item) {
        return item.answer == 0
      })) {
    alert("请选择正确选项");
    return
  }
  var sendData = {
    differServ: differServ,
    typeName: typeName,
    questionType: questionType,
    title: title,
    fileId: fileId,
    parse: parse,
    parseFileId: parseFileId,
    options: JSON.stringify(option),
    Token: salt,
    id: id
  }
  console.log(sendData);

  $.post(url + 'question/editQuestion', sendData, function (data) {
    if (data.code == 0) {
      layer.alert("修改成功", {
        btn: ['确定'] //按钮
      }, function (index) {
        layer.close(index);
        history.go(-1);

      });
    } else {
      alert(data.msg);
    }
    console.log(data);
  })
})

//删除选项
$("body").on("click", ".icon-guanbi", function () {
  if ($(".option").length > 2) {
    $(this).parents(".option").remove();
  }
  sortOption()
});

function getData() {
  $.post(url + 'question/getInfo', {Token: salt, id: id}, function (data) {
    if (data.code == 0) {
      var data = data.data;
      var list = JSON.parse(data.options);
      list.forEach(function (item) {
        if (item.fileId) {
          item.fileId = item.fileId.split(",");
        }
      })
      app.list = list;
      app.questionType = optionType = data.questionType;
      if (data.fileId!=null&&data.fileId!='null'&&data.fileId!='undefined') {
        data.fileId = data.fileId.split(",");
      }
      if (data.parseFileId) {
        data.parseFileId = data.parseFileId.split(",");
      }
      app.info = data;
      $("#differServ").val(data.differServ);
      $("#typeName").val(data.typeName);
      $("#questionType").val(data.questionType);
      $("#title").val(data.title);
      $("#parse").val(data.parse);
      sortOption()
    } else {
      alert(data.msg);
    }

  })
}


function getField($this) {
  var arr = [];
  $this.parent().find(".delImg").each(function () {
    arr.push($(this).attr("id"));
  })
  return arr.length > 0 ? arr.toString() : ''
}


$("body").on("click", ".delImg", function () {
  $(this).parent().remove();
});